﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.SessionState;
using HouseAgencySite.Models;
using HouseAgencySite.Utils;
using HouseAgencySite.ViewModel;

namespace HouseAgencySite.Areas.Admin.Controllers
{

    public class AccountController : BaseController
    {
        private AgencyDBContext db = new AgencyDBContext();

        /// <summary>
        /// 用户名，密码
        /// </summary>
        /// <param name="logName"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost, ActionName("Login")]
        public ActionResult Login(FormCollection form)
        {
            string logName = string.Empty;
            string pwd = string.Empty;
            logName=form["logName"].Trim();
            pwd=form["pwd"].Trim();
            string password = Md5Helper.ToMD5(pwd);
            string strsql = string.Format(@"SELECT Guid,LogonName,UserPwd,UserName,Telephone,Email,UserType FROM Users WHERE LogonName =@LogonName AND UserPwd = @Pwd And IsNull(IsDelete,0)=0", logName, password);
            SqlParameter paramLogName = new SqlParameter("@LogonName",SqlDbType.NVarChar,36);
            SqlParameter paramPwd = new SqlParameter("@Pwd", SqlDbType.NVarChar, 36);
            paramLogName.Value = logName;
            paramPwd.Value = password;
            IList<LogUserInfo> list = db.Database.SqlQuery<LogUserInfo>(strsql,paramLogName,paramPwd).ToList();
            if (list.Count > 0)
            {
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                    1,
                    list[0].UserName,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    false,
                    "admins"
                    );
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
               
                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                Session["UserInfo"] = list[0];
                if (Request.UrlReferrer.LocalPath == "/Admin/Account/Login")
                {
                    return RedirectToAction("Index","Home","Admin");
                }
                else
                {
                    if (Url.IsLocalUrl(Request.UrlReferrer.AbsoluteUri))
                        return RedirectToAction(Request.UrlReferrer.AbsoluteUri);
                    else
                        return Redirect("~/");
                }
            }
            else
            {
                return Content("用户名或密码错误，请重新输入!");
            }

        }

        /// <summary>
        /// 验证emial是否合法
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckEmail()
        {
            string email = Request["email"];
            string strsql = @"SELECT Email FROM Users WHERE Email =@Email";
            SqlParameter paramEmail = new SqlParameter("@Email", SqlDbType.NVarChar, 36);
            paramEmail.Value = email;
            IList<string> list = db.Database.SqlQuery<string>(strsql, paramEmail).ToList();
            if (list.Count > 0)
                return Content("ok");
            else
                return Content("no");

        }


        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        [ActionName("LoginOff")]
        public ActionResult LoginOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [ActionName("Login")]
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <returns></returns>
        public ActionResult ForgetPassWord()
        {
            return View();
        }


        /// <summary>
        /// 发送邮件 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SendMail()
        {
            string email = Request["email"];
            SmtpSending smtp = new SmtpSending();
            smtp.SetUp();
            smtp.To = email;
            smtp.HtmlMessageSendShouldSucceed("重置密码", email);
            return Content("邮件发送成功！");
        }

        /// <summary>
        /// 修改密码界面
        /// </summary>
        /// <returns></returns>
        public ActionResult ChangePassWord()
        {
            string email = Request["email"];
            ViewBag.Email = email;
            return View();
        }

        /// <summary>
        /// 修改密码（根据邮箱地址 修改对应密码）
        /// </summary>
        /// <returns></returns>
        [HttpPost,ActionName("change-pwd")]
        public ActionResult ChangePassWordConfirm()
        {
            string email = Request["email"];
            string userPwd = Request["password"];
            string strsql = @"UPDATE [Users]
   SET  [UserPwd] = @UserPwd WHERE [Email] =@Email";
            SqlParameter paramEmail = new SqlParameter("@Email", SqlDbType.NVarChar, 36);
            SqlParameter paramPwd = new SqlParameter("@UserPwd", SqlDbType.NVarChar, 36);
            paramEmail.Value = email;
            paramPwd.Value = userPwd;
            int result = db.Database.ExecuteSqlCommand(strsql,paramEmail,paramPwd);
            if (result > 0)
            {
                return Content("密码修改成功！");
            }
            else
            {
                return Content("密码修改失败！");
            }
        }
    }
}
